/*
 * @Author: wangming
 * @Date: 2021-03-30 16:05:05
 * @LastEditors: wangming
 * @LastEditTime: 2022-05-12 16:06:38
 * @Description: 设计器相关数据状态管理
 */

import { transformModelTree } from '@/utils/common';//tree找平
import { cloneDeep, merge } from 'lodash';
import { getHmentitymodelList } from '@/apis/paas/HmEntityModelController.js'
import { FormDataJSON } from '@/pageConfig/index.js'
const exclude = ['PICTURE', 'ATTACHMENT']; //排除图片和附件
const state = {
  formList: [], //针对表单内部组件list 已经打平
  formId: '', //万能页面选中所在表单的moduleId
  modelForm: {}, //被选中组件的包含key数据对象
  modelTreeList: [], //所有拖入设计器内的默认布局的组件tree 结构
  entitymodelList: [], // 表单模型对应的属性字段
  FormDataJSON: cloneDeep(FormDataJSON), //页面表单属性
  templateDate: {
    //模态框 预览或者编辑临时数据
    FormData: cloneDeep(FormDataJSON),
    formList: [],
  },
  navName: 'home', //导航默认主页
  authBypage: [],//操作权限
  layoutHistoryForId: '',//设计器历史记录缓存的id
};
const mutations = {
  uploadAuthBypage(state, authBypage) {
    state.authBypage = authBypage;
  },
  changeModelForm(state, modelForm) {
    // 变更选中组件
    state.modelForm = modelForm;
  },
  changeModelTree(state, list) {
    // 变更状态
    state.modelTreeList = list;
  },
  changeEntitymodelList(state, list) {
    // 变更状态
    state.entitymodelList = cloneDeep(list);
  },
  /**
   * 设置表单属性
   * @param {*} state
   * @param {*} FormData
   */
  changeFormData: (state, FormData) => {
    state.FormDataJSON = merge({}, FormDataJSON, FormData)
  },
  changeTemplateDate: (state, templateDate) => {
    state.templateDate = templateDate;
  },
  changeNavName: (state, name) => {
    state.navName = name;
  },
  changeFormId: (state, formId) => {
    state.formId = formId;
  },
  changeFormList: (state, formList) => {
    state.formList = formList;
  },
  changeHistoryId(state, id) {
    state.layoutHistoryForId = id
  }
};
const actions = {
  setAuthBypage({ commit }, authBypage) {
    commit('uploadAuthBypage', authBypage);
  },
  /**
   * 设置选中模版内容保存
   * @param {*} param0
   * @param {*} templateDate
   */
  setTemplateDate({ commit }, templateDate) {
    commit('changeTemplateDate', templateDate);
  },
  /**
   * 设置表单data
   * @param {*} param0
   * @param {*} FormData
   */
  setFormData({ commit }, FormData) {
    commit('changeFormData', FormData || {});
  },
  /**
   * 设置选中组件form
   * @param {*} param0
   * @param {*} modelForm
   */
  setModelForm({ commit }, modelForm) {
    commit('changeModelForm', modelForm);
  },
  setModelList({ commit }, list) {
    commit('changeModelTree', list);
  },
  setAllEntitymodelList({ commit }, list) {
    let Flist = list.filter((i) => i.status === 'PUBLISHED');
    commit('changeEntitymodelList', Flist);
  },
  setNavName({ commit }, name) {
    if (name === 'home') {
      //模版重置
      commit('changeTemplateDate', { FormData: cloneDeep(FormDataJSON), formList: [] });
    }
    commit('changeModelForm', {});
    commit('changeNavName', name);
  },
  async setForm({ commit, dispatch }, formId) {
    commit('changeFormId', formId);
    if (!!formId) {
      let hmentitymodelList = await getHmentitymodelList({
        modelKey: formId,
        activated: true,
      });
      dispatch('setAllEntitymodelList', hmentitymodelList)
    } else {
      dispatch('setAllEntitymodelList', [])
    }
  },
  setHistoryId({ commit }, id) {
    commit('changeHistoryId', id);
  },
  UpdateFormData({ commit }, formData) {
    const { key, js, css } = formData
    const _formData = cloneDeep(state.FormDataJSON)
    const _templateData = cloneDeep(state.templateDate)
    // 模态框 内修改pc
    _formData.template.forEach(item => {
      if (item.FormData.key === key) {
        item.FormData.js = js
        item.FormData.css = css
      }
    });
    if (key === _formData.key) {
      // pc pc在模态框
      _formData.js = js
      _formData.css = css
    }
    if (key === _templateData?.FormData.key) {
      // 模态框
      _templateData.FormData.js = js
      _templateData.FormData.css = css
      commit('changeTemplateDate', _templateData);
    }
    commit('changeFormData', _formData);
  }
};
const getters = {
  getHistoryForId: ({ layoutHistoryForId }) => {
    return layoutHistoryForId
  },
  getFormList: ({ formList }) => {
    return transformModelTree(formList, ['hlTableAdd']);
  },
  getFormId: ({ formId }) => {
    return formId;
  },
  getNavName: ({ navName }) => {
    return navName;
  },
  getTemplateDate: ({ templateDate }) => {
    return templateDate;
  },
  /**
   * 选中组件对象
   * @param {*} param0
   * @returns
   */
  getFormData: ({ FormDataJSON, navName, templateDate }) => {
    if (navName === 'template') {
      return templateDate.FormData;
    } else {
      return FormDataJSON;
    }
  },
  /**
 * 选中组件对象主页面
 * @param {*} param0
 * @returns
 */
  getFormDataForMain: ({ FormDataJSON }) => {
    return FormDataJSON;
  },
  getModelForm: ({ modelForm }) => {
    return modelForm;
  },
  /**
   * 大纲tree
   * @param {*} param0
   * @returns
   */
  getModelTreeList: ({ modelTreeList, navName, FormDataJSON, templateDate }) => {
    //栅格组件做特殊处理
    if (navName === 'template') {
      return transformLayoutTree(templateDate.formList);
    } else {
      let { Aside, Footer, Header } = FormDataJSON.layout
      return transformLayoutTree([...modelTreeList, ...Aside, ...Footer, ...Header]);
    }
  },
  getFormListInTree: (state, { getModelTreeList }) => {
    let queen = [];
    let out = [];
    queen = queen.concat(getModelTreeList);
    while (queen.length) {
      let first = queen.shift();
      if (first.tagName === "hlLayoutForm") {
        let { modelCode, moduleId } = first.__config
        out.push({
          key: first.key,
          label: `${first.name}(${first.key})`,
          modelCode, moduleId
        });
      } else if (first?.children?.length > 0) {
        queen = [].concat(first.children, queen);
      }
    }
    return out;
  },
  //获取页面所有可获取组件实例的集合 包括模版 布局
  getComponentListByPage: ({ modelTreeList, FormDataJSON }) => {
    let { Aside, Footer, Header } = FormDataJSON.layout
    let template = FormDataJSON.template.map(i => i.formList).flat()
    let configlist = [...modelTreeList, ...Aside, ...Footer, ...Header, ...template]
    return transAllTagByTree(configlist)
  },
  //获取主页面的tree
  getMainPageList: ({ modelTreeList, FormDataJSON }) => {
    let { Aside, Footer, Header } = FormDataJSON.layout
    return [...modelTreeList, ...Aside, ...Footer, ...Header]
  },
  getEntitymodelList: ({ entitymodelList }) => {
    return entitymodelList;
  }
};
export default {
  state,
  mutations,
  actions,
  getters,
};

function transformLayoutTree(list) {
  return list.map((i) => {
    if (i.tagName === 'hlLayout') {
      let children = i.children
        .filter((j) => j.children.length > 0)
        .map((z) => z.children).flat()
      return Object.assign({}, i, { children: transformLayoutTree(children) });
    } else if (!!i.children?.length) {
      return Object.assign({}, i, {
        children: transformLayoutTree(i.children),
      });
    } else {
      return i;
    }
  });
}
/**
 * tree 递归平 获取所有组件config 包括布局 
 * @param {*} tree
 * @returns
 */
function transAllTagByTree(tree) {
  let queen = [];
  let out = [];
  queen = queen.concat(tree);
  while (queen.length) {
    let first = queen.shift();
    if (first?.children?.length > 0 && first.tagName !== "hlTableAdd") {
      queen = [].concat(first.children, queen);
    }
    if (first?.hlcustomBtn?.children?.length > 0) {
      queen = [].concat(first?.hlcustomBtn, queen);
    }
    out.push(first);
  }
  return out;
}
